import React from 'react';
import { Row, Col, Form, DatePicker, Input, InputNumber, Select, Radio } from 'antd';
import moment from 'moment';
import { Link } from 'umi';

import { getDict } from '@/utils/dataDictUtil';
import { useRequest, defaultFormatResult } from '@/hooks';
import { LABOUR_PERIOD_TYPE, PROBATION_PERIOD_TYPE } from '@/pages/Recruitment/dictionary';

import { SalaryMonthInput } from '@/pages/Recruitment/components/SalaryInput';
import { getPostApplyData } from '@/pages/WorkFlow/services';
import { getRecruitmentInfo } from '@/pages/Recruitment/Hire/service';
import { useNoLabourPeriod } from '@/pages/Recruitment/Hire/Communicate/hooks';
import { SelectPost } from '@/pages/Recruitment/containers/select';

// import { formatToThreePart } from '@/utils/utils';

const { Option } = Select;
const { TextArea } = Input;

export const getDictName = (value, dict, valueKey = 'value', textKey = 'text') =>
    dict.find(item => item[valueKey] === value)?.[textKey] ?? '';

export default function HireInfo({ form, renderItem, isEdit, oneLineLayout, commInfo, talentInfo }) {
    const { data: JOB_TYPE } = useRequest(() => getDict('jobNature'), { initialData: [] });
    const disabledDate = current => current && current < moment().startOf('day');
    const { loseDuty, dutyCode, organizationName, dutyName } = talentInfo;
    const [isInit, setIsInit] = React.useState(true);
    // 岗位未失效，展示服务端返回的字段
    const [orgName, setOrgName] = React.useState();
    const [entryDutyCodeInitialVal, setEntryDutyCodeInitialVal] = React.useState();
    const [curDuty, setCurDuty] = React.useState([]); // 当前岗位

    const { data: applyData = {} } = useRequest(() => getPostApplyData(commInfo?.hiDataId), {
        refreshDeps: [commInfo?.hiDataId],
        ready: !!commInfo?.hiDataId,
        initialData: {},
        ...defaultFormatResult
    });

    // 是否已经提交审批来判断是否能预览
    const { data: flowData } = useRequest(() => getRecruitmentInfo({ employId: applyData?.employId }), {
        refreshDeps: [applyData?.employId],
        ready: !!applyData?.employId,
        ...defaultFormatResult
    });

    const { isNoLabourPeriod, noLabourPeriodCheckbox, noLabourPeriodText } = useNoLabourPeriod({
        applyData,
        form,
        formItemId: 'recruitEmployInfoVO.labourPeriodNumber'
    });

    React.useEffect(() => {
        // loseDuty： 0 - 有效， 1 - 无效
        if (loseDuty === 1) {
            // 岗位失效，展示 --
            setOrgName('--');
            form.validateFields(['recruitEmployInfoVO.entryDutyCode']);
        } else {
            setEntryDutyCodeInitialVal(applyData?.entryDutyCode || dutyCode || undefined);
            setOrgName(organizationName || '--');
            setCurDuty([
                {
                    dutyCode: applyData?.entryDutyCode || dutyCode || undefined,
                    dutyAlias: applyData?.entryDutyName || dutyName || undefined,
                    levelName: ''
                }
            ]);
        }
    }, [loseDuty, organizationName, applyData?.entryDutyCode, dutyCode]);

    // 选择岗位，改变入职部门
    const handleChange = (val, option = {}) => {
        const v = option.props?.options?.organizationName || '--';
        setOrgName(v);
    };

    return (
        <>
            <Row>
                <Col span={12}>
                    <Form.Item label="入职岗位">
                        {renderItem(
                            form?.getFieldDecorator('recruitEmployInfoVO.entryDutyCode', {
                                initialValue: entryDutyCodeInitialVal,
                                rules: [
                                    {
                                        required: true,
                                        validator(rule, value, callback) {
                                            if (isInit && loseDuty) {
                                                setIsInit(false);
                                                callback('原岗位已失效，请选择其他岗位');
                                            } else if (!value) {
                                                callback('入职岗位不能为空');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <SelectPost
                                    needFiltered
                                    filterParams={{ recruitStatusList: [3] }}
                                    onChange={handleChange}
                                    curDuty={curDuty}
                                    style={{ width: '100%' }}
                                />
                            ),
                            applyData.entryDutyName,
                            isEdit
                        )}
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="入职部门">{orgName}</Form.Item>
                </Col>
            </Row>
            <Row>
                <Col span={14}>
                    <Form.Item style={{ paddingLeft: '3px' }} labelCol={{ span: 5 }} label="工作性质">
                        {renderItem(
                            form?.getFieldDecorator('recruitEmployInfoVO.workType', {
                                initialValue: applyData?.workType || JOB_TYPE?.[0]?.value,
                                rules: [
                                    {
                                        required: true,
                                        message: '工作性质不能为空'
                                    }
                                ]
                            })(
                                <Radio.Group>
                                    {JOB_TYPE.map(item => (
                                        <Radio value={item.value} key={item.value}>
                                            {item.text}
                                        </Radio>
                                    ))}
                                </Radio.Group>
                            ),
                            getDictName(applyData?.workType, JOB_TYPE),
                            isEdit
                        )}
                    </Form.Item>
                </Col>
            </Row>
            <Row>
                <Col span={12}>
                    <Form.Item label="建议入职时间">
                        {renderItem(
                            form?.getFieldDecorator('recruitEmployInfoVO.suggestedEntryTime', {
                                initialValue: moment(applyData?.suggestedEntryTime || undefined),
                                rules: [
                                    {
                                        required: true,
                                        message: '建议入职时间不能为空'
                                    }
                                ]
                            })(
                                <DatePicker
                                    disabledDate={disabledDate}
                                    showTime={{ format: 'HH:mm' }}
                                    format="YYYY-MM-DD"
                                    placeholder="请选择建议入职时间"
                                    style={{ width: '100%' }}
                                />
                            ),
                            applyData.suggestedEntryTime && moment(applyData.suggestedEntryTime).format('YYYY-MM-DD'),
                            isEdit
                        )}
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="劳动合同年限">
                        {renderItem(
                            <>
                                {form?.getFieldDecorator('recruitEmployInfoVO.labourPeriodNumber', {
                                    initialValue: applyData?.labourPeriodNumber || 3,
                                    rules: [
                                        {
                                            required: true,
                                            message: '劳动合同年限不能为空'
                                        }
                                    ]
                                })(<InputNumber disabled={isNoLabourPeriod} min={0} />)}
                                <span style={{ padding: '0 6px' }}></span>
                                {form?.getFieldDecorator('recruitEmployInfoVO.labourPeriodType', {
                                    initialValue: applyData?.labourPeriodType || LABOUR_PERIOD_TYPE?.[0].value
                                })(
                                    <Select
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                        style={{ width: 80 }}
                                        disabled={isNoLabourPeriod}
                                    >
                                        {LABOUR_PERIOD_TYPE.map(item => (
                                            <Option value={item.value} key={item.value}>
                                                {item.text}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                                <span style={{ padding: '0 6px' }}></span>

                                {noLabourPeriodCheckbox}
                            </>,

                            isNoLabourPeriod
                                ? noLabourPeriodText
                                : `${applyData?.labourPeriodNumber ?? ''}${getDictName(
                                      applyData?.labourPeriodType,
                                      LABOUR_PERIOD_TYPE
                                  )}`,
                            isEdit
                        )}
                    </Form.Item>
                </Col>
            </Row>
            <Row>
                <Col span={12}>
                    <Form.Item label="试用期月薪">
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            {renderItem(
                                form?.getFieldDecorator('recruitEmployInfoVO.probationMonthSalary', {
                                    initialValue: applyData?.probationMonthSalary,
                                    rules: [
                                        {
                                            required: true,
                                            message: '试用期月薪不能为空'
                                        }
                                    ]
                                })(
                                    <InputNumber
                                        // formatter={formatToThreePart}
                                        placeholder="请输入试用期月薪"
                                        style={{ width: '100%' }}
                                        min={0}
                                        formatter={val => SalaryMonthInput(val, true)}
                                        parser={val => SalaryMonthInput(val)}
                                    />
                                ),
                                applyData?.probationMonthSalary,
                                isEdit
                            )}
                            {(talentInfo?.employSalaryCurrencyCode || talentInfo?.companyCurrencyCode) && (
                                <span style={{ marginLeft: 8 }}>
                                    {talentInfo?.employSalaryCurrencyCode || talentInfo?.companyCurrencyCode}
                                </span>
                            )}
                        </div>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="试用期">
                        {renderItem(
                            <>
                                {form?.getFieldDecorator('recruitEmployInfoVO.probationPeriodNumber', {
                                    initialValue: applyData?.probationPeriodNumber || 6,
                                    rules: [
                                        {
                                            required: true,
                                            message: '试用期不能为空'
                                        }
                                    ]
                                })(<InputNumber min={0} />)}
                                <span style={{ padding: '0 6px' }}></span>
                                {form?.getFieldDecorator('recruitEmployInfoVO.probationPeriodType', {
                                    initialValue: applyData?.probationPeriodType || PROBATION_PERIOD_TYPE?.[0].value
                                })(
                                    <Select
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                        style={{ width: 80 }}
                                    >
                                        {PROBATION_PERIOD_TYPE.map(item => (
                                            <Option value={item.value} key={item.value}>
                                                {item.text}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </>,
                            `${applyData?.probationPeriodNumber ?? ''}${getDictName(
                                applyData?.probationPeriodType,
                                PROBATION_PERIOD_TYPE
                            )}`,
                            isEdit
                        )}
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item label="补充说明" {...oneLineLayout} {...(isEdit ? { help: '不超过200个字符' } : {})}>
                        {renderItem(
                            form?.getFieldDecorator('recruitEmployInfoVO.remark', {
                                initialValue: applyData?.remark
                            })(<TextArea maxLength={200} placeholder="请输入审批补充信息" style={{ height: 100 }} />),
                            applyData?.remark,
                            isEdit
                        )}
                    </Form.Item>
                </Col>
            </Row>
            {!isEdit && (
                <Row>
                    <Col span={24}>
                        <Form.Item label="通知时间" {...oneLineLayout}>
                            <span style={{ paddingRight: 6 }}>录用审批通过后系统自动发送录用通知邮件给录用候选人</span>
                            {flowData && (
                                <Link to={`/user/hireConfirm?employId=${applyData?.employId}&action=detail`}>
                                    预览录用信息
                                </Link>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
            )}
        </>
    );
}
